package fastClient;

import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.ScheduledFuture;
import protocol.Header;
import protocol.IOMessage;
import protocol.MessageType;

public class HeartBeatReqHandler extends ChannelInboundHandlerAdapter{

	private volatile ScheduledFuture<?> heartBeat;

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		// TODO Auto-generated method stub
		if(evt instanceof IdleStateEvent){
			
			IdleStateEvent event = (IdleStateEvent) evt;
			IOMessage heartMes = buildHeartBeat();
			
			switch(event.state()){
			
			case READER_IDLE:
				System.out.println("read idle");
				break;
			case WRITER_IDLE:
				System.out.println("Write idle");
				break;
			case ALL_IDLE:
				System.out.println("all idle");
				ctx.writeAndFlush(heartMes);
				break;	
			default:
				break;
			}
			
		}
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg){
		
		IOMessage message = (IOMessage) msg;

		if(message.getHeader() != null && message.getHeader().getType()
				                     == MessageType.HEARTBEAT_RESP.value()){

			System.out.println(" Client receive server heart beat message: --> " + message);
		}
		ctx.fireChannelRead(msg);
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		// TODO Auto-generated method stub
		super.exceptionCaught(ctx, cause);
	}
	
	private IOMessage buildHeartBeat(){
		
		IOMessage message = new IOMessage();
		Header header = new Header();
		header.setType(MessageType.HEARTBEAT_REQ.value());
		message.setHeader(header);
		message.setBody("");
		
		return message;
	}
}
